import collections


class Twitter(object):

    def __init__(self):
        self.u = collections.defaultdict(collections.deque)
        self.t = collections.defaultdict(collections.deque)
        self.index = 0
        self.bu = collections.defaultdict(set)

    def postTweet(self, userId, tweetId):
        """
        :type userId: int
        :type tweetId: int
        :rtype: None
        """
        self.u[userId].appendleft([self.index, userId, tweetId])
        self.t[userId].appendleft([self.index, userId, tweetId])
        for id in self.bu[userId]:
            self.t[id].appendleft([self.index, userId, tweetId])
        self.index += 1

    def getNewsFeed(self, userId):
        """
        :type userId: int
        :rtype: List[int]
        """
        if len(self.t[userId]) > 10:
            return [item[2] for item in self.t[userId]][:10]
        else:
            return [item[2] for item in self.t[userId]]

    def follow(self, followerId, followeeId):
        """
        :type followerId: int
        :type followeeId: int
        :rtype: None
        """
        self.bu[followeeId].add(followerId)
        left_list = self.t[followerId]
        right_list = self.u[followeeId]
        left_index = 0
        right_index = 0
        n1 = len(left_list)
        n2 = len(right_list)
        return_list = collections.deque()
        while left_index < n1 and right_index < n2:
            if left_list[left_index][0] > right_list[right_index][0]:
                return_list.append(left_list[left_index])
                left_index += 1
            else:
                if left_list[left_index][0] < right_list[right_index][0]:
                    return_list.append(right_list[right_index])
                    right_index += 1
                else:
                    return_list.append(right_list[right_index])
                    left_index += 1
                    right_index += 1
        while left_index < n1:
            return_list.append(left_list[left_index])
            left_index += 1
        while right_index < n2:
            return_list.append(right_list[right_index])
            right_index += 1
        self.t[followerId] = return_list

    def unfollow(self, followerId, followeeId):
        """
        :type followerId: int
        :type followeeId: int
        :rtype: None
        """
        if followerId in self.bu[followeeId]:
            self.bu[followeeId].remove(followerId)
            return_list = collections.deque()
            follower_list = self.t[followerId]
            for i in range(len(follower_list)):
                if follower_list[i][1] != followeeId:
                    return_list.append(follower_list[i])
            self.t[followerId] = return_list


obj = Twitter()
obj.postTweet(1, 1)
obj.follow(2, 1)
print(obj.getNewsFeed(2))
